package com.cloud.order.controller;

import com.cloud.order.converter.OrderForm2OrderDTOConverter;
import com.cloud.order.dto.OrderCreateDto;
import com.cloud.order.exception.OrderException;
import com.cloud.order.from.OrderForm;
import com.cloud.order.service.OrderServiceInf;
import com.netflix.discovery.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;

/**
 * describe:
 *
 * @author zhanghaixuan
 * @date 2018/09/11
 **/
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderServiceInf orderServiceInf;

    /**
     * 1.校验数据
     * @param orderForm
     * @param bindingResult
     * @return
     */
    @PostMapping("/create")
    public ResponseEntity create(@Valid OrderForm orderForm, BindingResult bindingResult){

        if (bindingResult.hasErrors()){
           log.error("[创建订单]参数不正确,orderForm={}",orderForm);
           throw new OrderException(bindingResult.getFieldError().getDefaultMessage());
        }

        OrderCreateDto convert = OrderForm2OrderDTOConverter.convert(orderForm);

        if(CollectionUtils.isEmpty(convert.getOrderDetailList())){
            log.error("购买的商品为空!,orderForm={}",orderForm);
            throw new OrderException("购买的商品不能为空!");
        }

        OrderCreateDto orderCreateDto = orderServiceInf.create(convert);

        return ResponseEntity.ok(orderCreateDto);
    }

	@PostMapping("/finish")
	public ResponseEntity finish(@RequestParam("orderId") String orderId){

		return ResponseEntity.ok(orderServiceInf.finish(orderId));
	}
}
